
$(document).ready(function() {
    var Main = {
        data() {
            return {
                activeName: 'first'
            };
        },
        methods: {
            handleClick(tab, event) {
                console.log(tab, event);
            },
            // 添加最新开奖信息
            addData() {
                let _this = this;
                var data = {
                    qihao: $("#qihao").val(),
                    kjDate: $("#kjDate").val(),
                    kj:  $("#kj").val(),
                    sj: $("#sj").val(),
                    zj: $("#zj").val()
                }

                $.ajax({
                    url: 'http://localhost:8809/fucai/3d/addData',
                    type: 'POST',
                    contentType: "application/json", // 指定请求体格式为 JSON
                    data: JSON.stringify(data),
                    success: function(response) {
                        console.log("请求成功:", response);
                        if (response > 0){
                            _this.$message({
                                message: '恭喜你，添加成功',
                                type: 'success'
                            });
                        }
                    },
                    error: function(xhr, status, error) {
                        console.log('Request failed:', status, error);
                    }
                });
            },
            // 添加推荐信息
            addOrUpdateTuijianData(){
                let _this = this;
                var data = {
                    tuijianQihao: $("#tuijian_qihao").val(),
                    tuijianRen: $("#tuijian_ren").val(),
                    tuijianSha1:  $("#tuijian_sha1").val(),
                    tuijianSha2: $("#tuijian_sha2").val(),
                    tuijianQima: $("#tuijian_qima").val()
                }

                $.ajax({
                    url: 'http://localhost:8809/fucai/3d/tuijian/addOrUpdateTuijianData',
                    type: 'POST',
                    contentType: "application/json", // 指定请求体格式为 JSON
                    data: JSON.stringify(data),
                    success: function(response) {
                        console.log("请求成功:", response);
                        _this.$message({
                            message: '恭喜你，' + response,
                            type: 'success'
                        });
                    },
                    error: function(xhr, status, error) {
                        console.log('Request failed:', status, error);
                    }
                });
            }
        }
    };

    var Ctor = Vue.extend(Main)
    new Ctor().$mount('#app')


    // 最新一期开机号
    const new_kj = "750";
    // 最新一期试机号
    const new_sj = "";

    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份补零
    const day = String(now.getDate()).padStart(2, '0');       // 日期补零
    $("#kjDate").val(year + "-" + month + "-" + day);
    $("#kj").val(new_kj);
    $("#sj").val(new_sj);

    //  获取最新数据并填充至页面
    getNewData();

    // 获取中奖号路数占比统计,填充至页面
    getZjLuStatistics(null);

    if (new_kj != ""){
        const new_kj_b = new_kj.substring(0, 1);
        const new_kj_s = new_kj.substring(1, 2);
        const new_kj_g = new_kj.substring(2, 3);
        const new_kj_hezhi = Number(new_kj_b) + Number(new_kj_s) + Number(new_kj_g);
        const new_kj_max = Math.max(new_kj_b, new_kj_s, new_kj_g);
        const new_kj_min = Math.min(new_kj_b, new_kj_s, new_kj_g);
        const new_kj_kuadu = Number(new_kj_max) - Number(new_kj_min);

        $(".new_data_kj").html(new_kj);
        $(".new_data_kj_kuadu").html(new_kj_kuadu);
        $(".new_data_kj_hezhi").html(new_kj_hezhi);
        $(".new_data_kj_hezhi_wei").html(new_kj_hezhi % 10);
    }

    if (new_sj != ""){
        const new_sj_b = new_sj.substring(0, 1);
        const new_sj_s = new_sj.substring(1, 2);
        const new_sj_g = new_sj.substring(2, 3);
        const new_sj_hezhi = Number(new_sj_b) + Number(new_sj_s) + Number(new_sj_g);
        const new_sj_max = Math.max(new_sj_b, new_sj_s, new_sj_g);
        const new_sj_min = Math.min(new_sj_b, new_sj_s, new_sj_g);
        const new_sj_kuadu = Number(new_sj_max) - Number(new_sj_min);

        $(".new_data_sj").html(new_sj);
        $(".new_data_sj_kuadu").html(new_sj_kuadu);
        $(".new_data_sj_hezhi").html(new_sj_hezhi);
        $(".new_data_sj_hezhi_wei").html(new_sj_hezhi % 10);
    }

    // 添加tip监听器
    addTipListener();

    // 计算推荐杀号剩余
    setTuijianShaShengyu();
});

/**
 * 初始化推荐期号
 */
function initTuijianQihao(defaultQihao){
    $("#tuijian_qihao option").remove();

    const qihaoNian = 2025;
    for (let i = 1; i <= 359; i++){
        let tuijian_qihao = qihaoNian + String(i).padStart(3, '0');
        let option = $("<option value='" + tuijian_qihao + "'>" + tuijian_qihao + "</option>");
        if (tuijian_qihao == defaultQihao){
            option = $("<option value='" + tuijian_qihao + "' selected>" + tuijian_qihao + "</option>");
        }
        $("#tuijian_qihao").append(option);
    }
}

/**
 * 根据数据库中数据设置推荐数据
 */
function setTuijianByDb(fucai3dTuijianList){

    // 删除页面数据,重新绘制
    $(".tuijian_data_tr").remove();

    fucai3dTuijianList.forEach(fucai3dTuijian =>{
        let trHtml = '<tr class="tuijian_data_tr">';
        trHtml = trHtml + '<td>' + fucai3dTuijian.tuijianRen + "</td>";
        trHtml = trHtml + '<td colspan="3">';
        trHtml = trHtml + '杀一:<span class="data_tuijian_sha1">';
        trHtml = trHtml + fucai3dTuijian.tuijianSha1;
        trHtml = trHtml + '</span>';
        trHtml = trHtml + ',杀二:<span class="data_tuijian_sha2">';
        trHtml = trHtml + fucai3dTuijian.tuijianSha2;
        trHtml = trHtml + '</span>';
        trHtml = trHtml + ',七码:<span class="data_tuijian_qima">';
        trHtml = trHtml + fucai3dTuijian.tuijianQima;
        trHtml = trHtml + '</span>';
        trHtml = trHtml + '</td>';
        trHtml = trHtml + '</tr>';

        $("#tuijian_sha1_shengyu").before(trHtml);

        if (fucai3dTuijian.tuijianRen == '袁慧贤'){
            let data_tuijian_yuanhuixian_shengyu = "0123456789";
            data_tuijian_yuanhuixian_shengyu = data_tuijian_yuanhuixian_shengyu.replace(fucai3dTuijian.tuijianSha2.charAt(0), "");
            data_tuijian_yuanhuixian_shengyu = data_tuijian_yuanhuixian_shengyu.replace(fucai3dTuijian.tuijianSha2.charAt(1), "");

            $(".data_tuijian_yuanhuixian_shengyu").html(data_tuijian_yuanhuixian_shengyu);
        }
    });

    setTuijianShaShengyu();
}
/**
 * 计算推荐杀号剩余
 */
function setTuijianShaShengyu(){
    // 杀一剩余
    var data_tuijian_sha1_shengyu = "0123456789";
    const sha1 = $(".data_tuijian_sha1");
    sha1.toArray().forEach(ele =>{
        data_tuijian_sha1_shengyu = data_tuijian_sha1_shengyu.replace($(ele).html(), "");
    });
    $(".data_tuijian_sha1_shengyu").html(data_tuijian_sha1_shengyu);

    // 杀二剩余
    var data_tuijian_sha2_shengyu = "0123456789";
    const sha2 = $(".data_tuijian_sha2");
    sha2.toArray().forEach(ele =>{
        const sha2Data = $(ele).html();
        data_tuijian_sha2_shengyu = data_tuijian_sha2_shengyu.replace(sha2Data.charAt(0), "");
        data_tuijian_sha2_shengyu = data_tuijian_sha2_shengyu.replace(sha2Data.charAt(1), "");
    });
    $(".data_tuijian_sha2_shengyu").html(data_tuijian_sha2_shengyu);
}

/**
 * 填充数据
 * @param data
 */
function fillData(data, isNew){

    $("#data_id").val(data.id)
    $(".data_qihao").html(data.qihao)
    $(".data_kj_date").html(data.kjDate);
    $(".data_zj").html(data.zj);
    $(".data_lin").html(data.lin);
    $(".data_dy").html(data.dy);
    const data_shengyu = "0123456789".replace(data.zjB, "").replace(data.zjS, "").replace(data.zjG, "")
        .replace(data.dyB, "").replace(data.dyS, "").replace(data.dyG, "");
    $(".data_shengyu").html(data_shengyu);
    $(".data_chong").html(data.zj);
    $(".data_gu").html(data.gu);
    $(".data_kj").html(data.kj);
    $(".data_sj").html(data.sj);
    $(".data_kj_kuadu").html(data.kjKuadu);
    $(".data_sj_kuadu").html(data.sjKuadu);
    $(".data_kj_hezhi").html(data.kjHezhi);
    $(".data_sj_hezhi").html(data.sjHezhi);
    $(".data_kj_hezhi_wei").html(data.kjHezhi % 10);
    $(".data_sj_hezhi_wei").html(data.sjHezhi % 10);
    $(".data_zj_lu").html(data.zjLu);
    let data_clg_duanzu_all = data.clgDuanzu;
    if (data.clgDuanzu1){
        data_clg_duanzu_all = data_clg_duanzu_all + " " + String(data.clgDuanzu1);
    }
    if (data.clgDuanzu2){
        data_clg_duanzu_all = data_clg_duanzu_all + "," + String(data.clgDuanzu2);
    }
    $(".data_kuadu").html(data.kuadu);
    $(".data_hezhi").html(data.hezhi);
    $(".data_hezhi_wei").html(data.hezhiWei);
    $(".data_jiou").html(data.jiou);
    $(".data_daxiao").html(data.daxiao);
    $(".data_xingtai").html(data.xingtai);
    $(".data_clgd").html(data.clgd);

    $(".data_lu_top1_sha").html(data.luTop1Sha);
    $(".data_sq_hezhi_wei_sha").html(data.sqHezhiWeiSha);
    $(".data_sq_kuadu_sha").html(data.sqKuaduSha);
    $(".data_qihao_wei_sha").html(data.qihaoWeiSha);
    $(".data_kj_date_wei_sha").html(data.kjDateWeiSha);
    $(".data_kj_kuadu_sha").html(data.kjKuaduSha);
    $(".data_sj_kuadu_sha").html(data.sjKuaduSha);
    $(".data_shang2_shi_hezhi_wei_sha").html(data.shang2ShiHezhiWeiSha);
    $(".data_clg_duanzu_all").html(data_clg_duanzu_all);


    // 设置杀号正确和不正确样式
    $(".date_sha_yangshi").toArray().forEach(ele =>{
        const data = $(ele).html();
        if (data == '正确'){
            $(ele).css("color", "green");
        }else {
            $(ele).css("color", "red");
        }
    });

    if (isNew){
        // 设置添加最新开奖数据的期号
        const newQihaoNian = String(data.qihao).substring(0, 4);
        const newQihao = String(Number(String(data.qihao).substring(4, 7)) + 1).padStart(3, '0');
        let newQihaoAll = newQihaoNian + newQihao;
        $("#qihao").val(newQihaoAll);

        // 初始化推荐期号
        initTuijianQihao(newQihaoAll);

        // 最新期分析数据填充
        $(".new_data_qihao").html(newQihaoAll)
        $(".new_data_zj").html(data.zj);
        $(".new_data_lin").html(data.lin);
        $(".new_data_dy").html(data.dy);
        $(".new_data_shengyu").html(data_shengyu);
        $(".new_data_chong").html(data.zj);
        $(".new_data_gu").html(data.gu);
        // 断组邻码后去重
        const new_data_duanzu_lin = String(String(data.zj) + String(data.gu)).replace(/(\w+)\1+/g, '$1');
        $(".new_data_duanzu_lin").html(new_data_duanzu_lin);
        const new_data_duanzu_chong = String(String(data.lin) + String(data.gu)).replace(/(\w+)\1+/g, '$1');
        $(".new_data_duanzu_chong").html(new_data_duanzu_chong);
        const new_data_duanzu_gu = String(String(data.zj) + String(data.lin)).replace(/(\w+)\1+/g, '$1');
        $(".new_data_duanzu_gu").html(new_data_duanzu_gu);

        // 查询推荐数据,查询完成后填充到页面
        queryTuijianData( newQihaoAll, null);
    }
}

/**
 * 填充往期中奖号路数占比统计
 */
function fillZjLuStatisticsWangqi(data){
    $("#zjLuStatistics_wangqi tbody tr").remove();
    $(".zjLuStatistics_wangqi_qihao").html($(".data_qihao").html());
    if (data && data.length > 0){
        for (let i = 0; i < data.length; i++) {
            const element = data[i];
            $("#zjLuStatistics_wangqi tbody").append("<tr>" +
                "<td>" + element.baiqiZjLu + "</td>" +
                "<td>" + element.baiqiZjLuQuantity + "</td>" +
                "</tr>");
        }
    }
}

/**
 * 填充最新中奖号路数占比统计
 */
function fillZjLuStatistics(data){
    $("#zjLuStatistics tbody tr").remove();
    if (data && data.length > 0){
        for (let i = 0; i < data.length; i++) {
            const element = data[i];
            $("#zjLuStatistics tbody").append("<tr>" +
                "<td>" + element.baiqiZjLu + "</td>" +
                "<td>" + element.baiqiZjLuQuantity + "</td>" +
                "</tr>");
        }
    }
}

/**
 * 获取上一期或下一期
 * @param type 0:上一期,1:下一期
 */
function getOtherData(type){
    var id = $("#data_id").val();
    if (type == 0){
        getDataById(Number(id) - 1);
        getZjLuStatistics(Number(id) - 1);
    }else if (type == 1){
        getDataById(Number(id) +1);
        getZjLuStatistics(Number(id) + 1);
    }
}

/**
 * 清空已选择的路号
 */
function clearSelectLuHaoma(){
    $(".hezhi_statistics_table_haoma_red").removeClass("hezhi_statistics_table_haoma_red");
}

/**
 * 根据选择路号选中号码
 * @param e
 * @param lu
 */
function selectLuHaoma(e, lu){
    // 添加选中样式
    $(e).toggleClass("pure-button-primary");
    // 按钮选中状态反选
    $(e).siblings().removeClass("pure-button-primary");

    let tableHaomas = $(".hezhi_statistics_table_haoma");
    for (let i = 0; i < tableHaomas.length; i++) {
        const element = tableHaomas[i];
        const eleLu = $(element).text();
        const c1 = eleLu.charAt(0);
        const c2 = eleLu.charAt(1);
        const c3 = eleLu.charAt(2);

        const lu1 = '0369'.includes(c1) ? '0' : '147'.includes(c1) ? '1' : '2';
        const lu2 = '0369'.includes(c2) ? '0' : '147'.includes(c2) ? '1' : '2';
        const lu3 = '0369'.includes(c3) ? '0' : '147'.includes(c3) ? '1' : '2';

        const zuLu = [];
        zuLu.push(String(lu1 + lu2 + lu3));
        zuLu.push(String(lu1 + lu3 + lu2));
        zuLu.push(String(lu2 + lu1 + lu3));
        zuLu.push(String(lu2 + lu3 + lu1));
        zuLu.push(String(lu3 + lu1 + lu2));
        zuLu.push(String(lu3 + lu2 + lu1));

        let have = false;
        zuLu.forEach(eleZuLu =>{
            if (eleZuLu == lu){
                have = true;
                return;
            }
        })

        if (have){
            $(element).addClass("hezhi_statistics_table_haoma_red");
        }else {
            $(element).removeClass("hezhi_statistics_table_haoma_red");
        }
    }
}


/**
 * 查询推荐数据
 */
function queryTuijianData(tuijianQihao, tuijianRen){
    var data = {
        tuijianQihao: tuijianQihao,
        tuijianRen: null
    }
    $.ajax({
        url: 'http://localhost:8809/fucai/3d/tuijian/queryTuijianData',
        type: 'POST',
        contentType: "application/json", // 指定请求体格式为 JSON
        data: JSON.stringify(data),
        success: function(response) {
            console.log("请求成功:", response);
            // 根据数据库中数据设置推荐数据
            setTuijianByDb(response);
        },
        error: function(xhr, status, error) {
            console.log('Request failed:', status, error);
        }
    });
}


/**
 * 获取最新一期数据
 */
function getNewData(){
    $.ajax({
        url: 'http://localhost:8809/fucai/3d/getNewData',
        type: 'GET',
        success: function(response) {
            console.log("请求成功:", response);
            fillData(response, true);

            // 获取中奖号路数占比统计
            getZjLuStatistics(response.id);
        },
        error: function(xhr, status, error) {
            console.log('Request failed:', status, error);
        }
    });
}

/**
 * 根据ID获取数据
 */
function getDataById(id){
    $.ajax({
        url: 'http://localhost:8809/fucai/3d/getDataById',
        type: 'GET',
        data: {
            id: id
        },
        success: function(response) {
            console.log("请求成功:", response);
            if (null == response || response.length == 0){
                new LightTip().error('数据不存在');
                return;
            }
            fillData(response, false);
            // 获取中奖号路数占比统计
            getZjLuStatistics(response.id);
        },
        error: function(xhr, status, error) {
            console.log('Request failed:', status, error);
        }
    });
}

/**
 * 中奖号路数占比统计
 */
function getZjLuStatistics(id){
    $.ajax({
        url: 'http://localhost:8809/fucai/3d/getZjLuStatistics',
        type: 'GET',
        data: {
            id: id,
            qiQuantity: 100
        },
        success: function(response) {
            console.log("请求成功:", response);
            if (null == response || response.length == 0){
                new LightTip().error('数据不存在');
                return;
            }
            if (null != id){
                fillZjLuStatisticsWangqi(response);
            }else {
                fillZjLuStatistics(response);
            }
        },
        error: function(xhr, status, error) {
            console.log('Request failed:', status, error);
        }
    });
}

/**
 * TOP提示监听器
 */
function addTipListener(){
    // 创建 tooltip 元素
    const $tooltip = $('<div class="jquery-tooltip"></div>').appendTo('body');

    // 鼠标悬停事件
    $('.tooltip-trigger').on({
        mouseenter: function(e) {
            const tooltipText = $(this).attr('data-tooltip');
            if (!tooltipText) return;

            $tooltip.text(tooltipText);

            // 延迟显示
            setTimeout(() => {
                $tooltip.css({ display: 'block' });
                updateTooltipPosition(e);
                $tooltip.css({ opacity: '1', transform: 'translateY(0)' });
            }, 200);
        },

        mouseleave: function() {
            $tooltip.css({ opacity: '0', transform: 'translateY(5px)' });
            setTimeout(() => {
                $tooltip.css({ display: 'none' });
            }, 200);
        },

        mousemove: function(e) {
            updateTooltipPosition(e);
        }
    });

    // 更新 tooltip 位置
    function updateTooltipPosition(e) {
        const tooltipWidth = $tooltip.outerWidth();
        const tooltipHeight = $tooltip.outerHeight();
        const windowWidth = $(window).width();
        const windowHeight = $(window).height();

        // 默认位置：鼠标右下方
        let left = e.pageX + 15;
        let top = e.pageY + 15;

        // 防止超出窗口右侧
        if (left + tooltipWidth > windowWidth) {
            left = e.pageX - tooltipWidth - 15;
        }

        // 防止超出窗口底部
        if (top + tooltipHeight > windowHeight) {
            top = e.pageY - tooltipHeight - 15;
        }

        // 防止超出窗口左侧
        if (left < 0) {
            left = 10;
        }

        // 防止超出窗口顶部
        if (top < 0) {
            top = 10;
        }

        $tooltip.css({ left: left + 'px', top: top + 'px' });
    }
}



